package com.aps.apspda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.AlarmListAdapter;
import com.aps.apspda.adapter.InputDataListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.dialog.LoadingDialog;
import com.aps.apspda.entity.AlarmEntity;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.InputDataEntity;
import com.aps.apspda.entity.LotEndEntity;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.ActivityManager;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class EndFunctionActivity extends BaseActivity {


    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.tvLogId)
    TextView tvLogId;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.tvTouNum)
    TextView tvTouNum;
    @BindView(R.id.tvPlanNum)
    TextView tvPlanNum;
    @BindView(R.id.etTrueNum)
    EditText etTrueNum;
    @BindView(R.id.tvPassRate)
    TextView tvPassRate;
    @BindView(R.id.tvUph)
    TextView tvUph;
    @BindView(R.id.rvAlarmList)
    RecyclerView rvAlarmList;
    @BindView(R.id.etRemark)
    EditText etRemark;
    @BindView(R.id.tvSubmitRemark)
    TextView tvSubmitRemark;
    @BindView(R.id.rvInputList)
    RecyclerView rvInputList;
    @BindView(R.id.ivDownArrow2)
    ImageView ivDownArrow2;


    private LotEndEntity lotEndEntity;
    private AlarmListAdapter alarmListAdapter;
    private Animation animation, animationDismiss;
    private InputDataListAdapter inputDataListAdapter;
    private List<InputDataEntity.InputObject> inputList;
    private LoadingDialog dialog;


    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            EndFunctionActivity.this.finish();
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_end_function;
    }

    @Override
    protected void initView() {
        rvInputList.setLayoutManager(new LinearLayoutManager(EndFunctionActivity.this));
        rvInputList.setItemAnimator(new DefaultItemAnimator());
        rvInputList.addItemDecoration(new DividerItemDecoration(EndFunctionActivity.this, 1));

        rvAlarmList.setLayoutManager(new LinearLayoutManager(EndFunctionActivity.this));
        rvAlarmList.setItemAnimator(new DefaultItemAnimator());
        rvAlarmList.addItemDecoration(new DividerItemDecoration(EndFunctionActivity.this, 1));

        topView.setTitle("批次结束(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        topView.setTitleMode(TitleView.NORMAL_TEXT_MODE);
        topView.setRightListener("结束作业", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (etTrueNum.getText().toString().trim().length() == 0) {
                    ToastUtils.showFreeToast("请填写实际产量后再结束作业",
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (lotEndEntity != null) {
                    boolean isOk = true;
                    for (InputDataEntity.InputObject inputObject : inputList) {
                        if (inputObject.getISNULL().equalsIgnoreCase("Y")) {
                            if (inputObject.getDATAVALUE().length() == 0) {
                                isOk = false;
                                ToastUtils.showFreeToast("请填写带*栏数据", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                break;
                            }
                        }
                    }
                    if (isOk) {
                        if (getEqpID().toLowerCase().contains("fb") ||
                                getEqpID().toLowerCase().contains("fd")) {
                            requestEndWorkWithoutDialog();
                            if (dialog == null) {
                                dialog = new LoadingDialog();
                                dialog.setRequestTag("end_loading_dialog");
                            }
                            dialog.show(getSupportFragmentManager(), "end_loading_dialog");
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismissAllowingStateLoss();
                                    ToastUtils.showFreeToast("后台正在处理，请等待30秒再操作PDA",
                                            EndFunctionActivity.this, true, 3);
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            setResult(110);
                                            ActivityManager.getActivityManager().finishActivity(DbStartFunctionActivity.class);
                                            EndFunctionActivity.this.finish();
                                        }
                                    }, 3000);
                                }
                            }, 5000);
                        } else {
                            requestEndWork();
                        }
                    }
                }
            }

        });
    }

    private void requestEndWorkWithoutDialog() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new EntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType()) {
            @Override
            public void onSuccess(Response<BaseEntity<FinishLotEntity>> response) {

            }

            @Override
            public void onError(Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EndProcess");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EqpId", getEqpID());
        map.put("LotId", lotEndEntity.getLotId());
        map.put("DoneQty", etTrueNum.getText().toString().trim().length() == 0 ? "0" : etTrueNum.getText().toString().trim());
        map.put("Remark", etRemark.getText().toString().trim());
        JSONObject jsonObject = new JSONObject();
        try {
            if (inputList.size() == 0) {
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(inputList));
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", jsonArray));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        NetUtils.requestNet(this, "/EndProcess", map, callBack);
    }

    private void requestEndWork() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EndProcess");
            }

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    ToastUtils.showFreeToast("结束作业成功",
                            EndFunctionActivity.this, true, Toast.LENGTH_SHORT);
                    mHandler.postDelayed(runnable, 1000);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }

            }


        };

        Map<String, String> map = new HashMap<>();
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EqpId", getEqpID());
        map.put("LotId", lotEndEntity.getLotId());
        map.put("DoneQty", etTrueNum.getText().toString().trim().length() == 0 ? "0" : etTrueNum.getText().toString().trim());
        map.put("Remark", etRemark.getText().toString().trim());
        JSONObject jsonObject = new JSONObject();
        try {
            if (inputList.size() == 0) {
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(inputList));
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", jsonArray));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        NetUtils.requestNet(this, "/EndProcess", map, callBack);
    }

    @Override
    protected void initData() {
        requestData();
    }

    private void requestData() {
        EntityCallBack<BaseEntity<LotEndEntity>> callBack = new DialogEntityCallBack<BaseEntity<LotEndEntity>>
                (new TypeToken<BaseEntity<LotEndEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LotEndEntity>> response) {

                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    lotEndEntity = response.body().getData();
                    tvLogId.setText(lotEndEntity.getLotId());
                    tvEqpId.setText(lotEndEntity.getEqpId());
                    tvStartTime.setText(lotEndEntity.getTrackInTime());
                    tvEndTime.setText(lotEndEntity.getProcessEndTime());
                    tvTouNum.setText(lotEndEntity.getTotalQty());
                    tvPlanNum.setText(String.valueOf(Integer.parseInt(lotEndEntity.getDoneQty()) / 1000));
                    etTrueNum.setText(lotEndEntity.getTotalQty());
                    List<AlarmEntity> alarmEntityList = new ArrayList<>();
                    if (lotEndEntity.getMainAlarms().length() > 0) {
                        String[] strs = lotEndEntity.getMainAlarms().split(";");
                        for (String s : strs) {
                            String[] strings = s.split(":");
                            AlarmEntity alarmEntity = new AlarmEntity(strings[0], strings[1]);
                            alarmEntityList.add(alarmEntity);
                        }
                    }
                    alarmListAdapter = new AlarmListAdapter(alarmEntityList);
                    alarmListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    alarmListAdapter.isFirstOnly(true);
                    rvAlarmList.setAdapter(alarmListAdapter);

                    inputList = lotEndEntity.getINPUTDATALIST().getINPUTDATA();
                    inputDataListAdapter = new InputDataListAdapter(inputList);
                    inputDataListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    inputDataListAdapter.isFirstOnly(true);
                    rvInputList.setAdapter(inputDataListAdapter);

                    tvUph.setText(lotEndEntity.getUPH());
                    tvPassRate.setText(lotEndEntity.getYieID());
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    mHandler.postDelayed(runnable, 1000);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<LotEndEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEndProcess");
                mHandler.postDelayed(runnable, 1000);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/ShowEndProcess", map, callBack);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.tvSubmitInput, R.id.tvSubmitRemark, R.id.rlInput})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.tvSubmitInput:
                boolean isInputOk = true;
                for (InputDataEntity.InputObject inputObject : inputList) {
                    inputObject.setEQPID(getEqpID());
                    if (isInputOk) {
                        if (inputObject.getISNULL().equalsIgnoreCase("Y")) {
                            if (inputObject.getDATAVALUE().length() == 0) {
                                ToastUtils.showFreeToast("请填写带*栏数据", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                isInputOk = false;
                            }
                        }
                    }
                }
                if (isInputOk) {
                    requestInputData();
                }
                break;
            case R.id.tvSubmitRemark:
                if (etRemark.getText().toString().trim().length() > 0) {
                    if (lotEndEntity != null) {
                        StartFunctionActivity.requestSubmitRemark(getEqpID(),
                                lotEndEntity.getLotId(), etRemark.getText().toString(), EndFunctionActivity.this, getSupportFragmentManager());
                    } else {
                        ToastUtils.showFreeToast("lot信息还未请求成功",
                                EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    }
                } else {
                    ToastUtils.showFreeToast("请填写备注后再提交",
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
                break;
            case R.id.rlInput:
                if (rvInputList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animationDismiss);
                    rvInputList.setVisibility(View.GONE);
                } else {
                    if (animation == null) {
                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setDuration(500);
                        animation.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animation);
                    rvInputList.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void requestInputData() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    ToastUtils.showFreeToast("提交数据成功",
                            EndFunctionActivity.this, true, Toast.LENGTH_SHORT);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "SubmitInputData");
            }
        };

        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        try {
            if (inputList.size() == 0) {
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(inputList));
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", jsonArray));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/SubmitInputData", map, callBack);
    }

//    private void test(){
//        List<String> eqpTypeList = new ArrayList<>();
//        List<String> data = new ArrayList<>();
//
//
//        JSONArray jsonArray = new JSONArray();
//        for (int i = 0; i < eqpTypeList.size(); i++) {
//            JSONObject jsonObject = new JSONObject();
//            JSONArray  jsonArray2 = new JSONArray();
//            String currentType =eqpTypeList[i].EQP_TYPE;
//            for (int j = 0; j < data.size(); j++) {
//
//                JSONObject jsonObject1 = new JSONObject();
//                String eqpType2 = data[j].EQP_TYPE;
//                if (currentType.equals(eqpType2)) {
//                    jsonObject1.put('eqpId', data[j].EQUIPMENT_ID)
//                    jsonObject1.put('color', data[j].COLOR)
//                }
//                jsonArray2.put(jsonObject1);
//            }
//            try {
//                jsonObject.put("'eqpType'", currentType);
//                jsonObject.put("'eqpinfo'", jsonArray2);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            jsonArray.put(jsonObject);
//        }
//    }
}
